// Copyright 2023 Innkeeper Lukexp(王晓平) &lt;37196496@qq.com>. All rights reserved.
// Use of this source code is governed by a MIT style
// license that can be found in the LICENSE file. The original repo for
// this file is https://gitee.com/jetxt/jinyu.

package app

import (
	"flag"
	"fmt"

	"github.com/spf13/viper"
)

const defaultConfigFile = "config.yaml"

func Viper(opts APPOptions, path ...string) *viper.Viper {
	var config string
	if len(path) == 0 {
		flag.StringVar(&config, "c", "", "choose config file.")
		flag.Parse()
		if config == "" { // 优先级: 命令行 > 环境变量 > 默认值
			config = defaultConfigFile
		} else {
			fmt.Printf("您正在使用命令行的-c参数传递的值,config的路径为%v\n", config)
		}
	} else {
		config = path[0]
		fmt.Printf("您正在使用func Viper()传递的值,config的路径为%v\n", config)
	}
	v := viper.New()
	v.SetConfigFile(config)
	err := v.ReadInConfig()
	if err != nil {
		fmt.Println("Cannot load config file,use default config to start server")
		return v
	}
	if err := v.Unmarshal(&opts); err != nil {
		fmt.Println(err)
	}
	return v
}
